package com.bosssoft.g4.service.impl;

import cn.hutool.core.util.IdUtil;
import com.bosssoft.common.exception.BaseException;
import com.bosssoft.common.util.MyBeanUtil;
import com.bosssoft.g4.bo.ResourceTree;
import com.bosssoft.g4.bo.SubSystemTree;
import com.bosssoft.g4.dto.ResourceDTO;
import com.bosssoft.g4.dto.SubSystemDTO;
import com.bosssoft.g4.entity.Resource;
import com.bosssoft.g4.mapper.ResourceMapper;
import com.bosssoft.g4.service.ResourceService;
import com.bosssoft.g4.service.SubSystemService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import javax.validation.constraints.NotNull;
import java.util.*;

/**
 * @author Baiye959
 */
@Slf4j
@Service
@Validated
public class ResourceServiceImpl implements ResourceService {
    @Autowired
    private ResourceMapper resourceMapper;
    @Autowired
    private SubSystemService subSystemService;

    @Override
    public List<ResourceDTO> getResourceList(ResourceDTO resourceDTO) {
        Resource resource = new Resource();
        BeanUtils.copyProperties(resourceDTO, resource);
        return resourceMapper.selectResourceList(resource);
    }

    @Override
    public ResourceDTO getResourceById(@NotNull Long id) {
        return resourceMapper.selectResourceById(id);
    }

    @Override
    public Boolean deleteResourceById(@NotNull Long id) {
        if (id == null) {
            throw new BaseException("id不能为空");
        }
        return resourceMapper.deleteResourceById(id);
    }

    @Override
    public Boolean deleteResourceByIdList(@NotNull List<Long> idList) {
        if (idList == null) {
            throw new BaseException("idList不能为空");
        }
        return resourceMapper.deleteResourceByIdList(idList);
    }

    @Override
    public Boolean updateResource(@NotNull ResourceDTO resourceDTO) {
        if (resourceDTO == null) {
            throw new BaseException("资源不能为空");
        }
        Resource resource = new Resource();
        BeanUtils.copyProperties(resourceDTO, resource);
        resource.setOrgId(1337955940401545216L);
        return resourceMapper.updateResource(resource);
    }

    // todo @Transactional
    @Override
    public Long insertResource(@NotNull ResourceDTO resourceDTO) {
        if (resourceDTO == null) {
            throw new BaseException("资源不能为空");
        }
        Resource resource = new Resource();
        BeanUtils.copyProperties(resourceDTO, resource);
        Long id = IdUtil.getSnowflake(1, 1).nextId();
        resource.setId(id);
        resource.setOrgId(1337955940401545216L);
        resource.setLeaf(0);
        resource.setAction(0);
        resource.setCreatedBy(1L);
        resource.setUpdatedBy(1L);
        resource.setVersion(1L);
        Long changedRowCnt = resourceMapper.insertResource(resource);
        // todo 插入basic_role_resource表
        return changedRowCnt;
    }

    public List<ResourceTree> getResourceTreeBySubSystemId(@NotNull Long subSystemId) {
        if (subSystemId == null) {
            throw new BaseException("子系统id不能为空");
        }
        List<ResourceDTO> resourceDTOList = resourceMapper.selectResourceListBySubSystemId(subSystemId);
        return MyBeanUtil.copyList(resourceDTOList, ResourceTree::new, (source, target) -> {
            target.setLabel(source.getName()); // 将ResourceDTO的name赋值给ResourceTree的label
        });
    }

    @Override
    public List<SubSystemTree> getResourceTree() {
        List<SubSystemDTO> subSystemDTOList = subSystemService.getSubSystemList();
//        log.info("subSystemDTOList:{}", subSystemDTOList);
        List<SubSystemTree> subSystemTreeList = new ArrayList<>();
        for (SubSystemDTO subSystemDTO : subSystemDTOList) {
            List<ResourceTree> resourceTreeList = getResourceTreeBySubSystemId(subSystemDTO.getId());
//            log.info("resourceDTOList:{}", resourceDTOList);
            if (resourceTreeList == null || resourceTreeList.isEmpty()) {
                continue;
            }
            subSystemTreeList.add(listToTree(resourceTreeList));
        }
        return subSystemTreeList;
    }

    private SubSystemTree listToTree(List<ResourceTree> list) {
        if (list == null || list.isEmpty()) {
            return null;
        }
//        ResourceTree(id=1433548548871421952, name=自动化测试系统, parentId=-1, children=null)
//        log.info("listToTree - list:{}", list);

        // todo: 列表转树
        // 填充subSystemTree的名字
        SubSystemTree subSystemTree = new SubSystemTree();
        subSystemTree.setSubsystemName(list.get(0).getLabel());
        // 创建一个 id 到 ResourceTree 的映射
        Map<Long, ResourceTree> resourceMap = new HashMap<>();
        for (ResourceTree resource : list) {
            resourceMap.put(resource.getId(), resource);
        }
        // 填充subSystemTree的children
        List<ResourceTree> children = new ArrayList<>();
        for (ResourceTree resource : list) {
            if (resource.getParentId() == -1) {
                // 当前节点为根节点
                children.add(resource);
            } else {
                // 获取当前节点的父节点
                ResourceTree parent = resourceMap.get(resource.getParentId());
                if (parent != null) {
                    if (parent.getChildren() == null) {
                        parent.setChildren(new ArrayList<>());
                    }
                    // 将当前节点加入父节点的 children 中
                    parent.getChildren().add(resource);
                } else {
                    log.error("父节点不存在，id:{}", resource.getParentId());
                }
            }
        }
//        log.info("listToTree - children:{}", children);

        subSystemTree.setChildren(children);

//        log.info("listToTree - subSystemTree:{}", subSystemTree);
        return subSystemTree;
    }
}
